package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;
    /**
     * 每一分钟执行一次，未支付的订单超过15分钟，变更状态为取消订单
     */
//    @Scheduled(cron = "0 * * * * ?")
    // @Scheduled(cron = "5/10 * * * * ?")
    public void noPay(){
        log.info("超时订单，取消订单：{}", LocalDateTime.now());

        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
        //select * from orders where status=? and create_time < 当前时间-15
        List<Orders> ordersList =  ordersMapper.getByStatusAndCreateTimeLT(Orders.PENDING_PAYMENT,localDateTime);

        if(ordersList!=null && ordersList.size()>0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时未支付");
                orders.setCancelTime(LocalDateTime.now());

                ordersMapper.update(orders);
            }
        }
    }

    /**
     * 凌晨一点检查是否还有派送中的订单，把订单状态给为已完成  order_time< 00:00:00
     */
    @Scheduled(cron = "0 0 1 * * ?")
    // @Scheduled(cron = "0/5 * * * * ?")
    public void noComplate(){
        log.info("未完成订单，改成已完成：{}", LocalDateTime.now());

        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-60);
        //select * from orders where status=? and create_time < 当前时间-15
        List<Orders> ordersList =  ordersMapper.getByStatusAndCreateTimeLT(Orders.DELIVERY_IN_PROGRESS,localDateTime);

        if(ordersList!=null && ordersList.size()>0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                ordersMapper.update(orders);
            }
        }
    }

}
